package com.java.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.java.entity.BsAppraise;
import com.java.entity.BsAppraiseRecord;
import com.java.entity.BsCourse;
import com.java.entity.BsCourseTarget;
import com.java.entity.BsScoreRecord;
import com.java.entity.BsStudent;
import com.java.entity.ext.BsAppraiseVo;
import com.java.entity.ext.DegreeInfo;
import com.java.entity.ext.WorkInfo;
import com.java.mapper.BsAppraiseMapper;
import com.java.mapper.BsAppraiseRecordMapper;
import com.java.mapper.BsCourseMapper;
import com.java.mapper.BsCourseTargetMapper;
import com.java.mapper.BsScoreRecordMapper;
import com.java.mapper.BsStudentMapper;
import com.java.service.BsAppraiseService;
import com.java.util.MyMap;
import com.java.util.MyTools;
import com.java.util.resp.BaseRespone;
import com.java.util.resp.TableRespone;

@Service
public class BsAppraiseServiceImpl implements BsAppraiseService {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired private BsAppraiseMapper appraiseMapper;
    @Autowired private BsAppraiseRecordMapper recordMapper;
    @Autowired private BsStudentMapper studentMapper;
    @Autowired private BsCourseMapper courseMapper;
    @Autowired private BsCourseTargetMapper targetMapper;
    @Autowired private BsScoreRecordMapper scoreRecordMapper;
    
	@Override
	public TableRespone getAppraises(String studentId, String courseId, String remark, int page, int size) {
		MyMap mm = new MyMap().put("appraiseDelete", 0)
				.put("appraiseStudentId", studentId)
				.put("appraiseCourseId", courseId)
				.put("appraiseRemark", remark);
		int offset = TableRespone.getOffset(page, size);
		List<BsAppraise> list = appraiseMapper.selectAll(mm, offset, size);
		List<BsAppraise> count = appraiseMapper.selectAll(mm, 0, 0);
		List<BsAppraiseVo> clist = new ArrayList<BsAppraiseVo>();
		if(count.size() > 0) {
			for (BsAppraise appraise : list) {
				BsStudent s = studentMapper.selectByKey(appraise.getAppraiseStudentId());
				BsCourse c = courseMapper.selectByKey(appraise.getAppraiseCourseId());
				BsCourseTarget t = targetMapper.selectByKey(appraise.getAppraiseTargetId());
				clist.add(new BsAppraiseVo(appraise, s, c, t));
			}
		}
		return new TableRespone(clist, count.size());
	}
	
	@Override
	public BaseRespone saveAppraise(BsAppraise appraise) {
		int row = 0;
		BsAppraise info = appraiseMapper.selectByKey(appraise.getAppraiseId());
		//BsCourseTarget t = targetMapper.selectByKey(appraise.getAppraiseTargetId());
		if(null == info) {
			BsScoreRecord sRecord = scoreRecordMapper.selectRecord(appraise.getAppraiseStudentId(), appraise.getAppraiseCourseId(), appraise.getAppraiseTargetId());
			if(null == sRecord) {
				return BaseRespone.error("该学生的课程目标项暂未设置");
			}
			if(null == sRecord.getRecordScore()) {
				return BaseRespone.error("该学生的课程目标项暂未打分");
			}
			appraise.setAppraiseId(MyTools.getUUID());
			appraise.setAppraiseRecordId(sRecord.getRecordId());
			appraise.setAppraiseTime(new Date());
			appraise.setAppraiseDelete(0);
			row = appraiseMapper.insertSelective(appraise);
		}else {
			row = appraiseMapper.updateSelective(appraise);
		}
		if(row > 0) {
			return BaseRespone.success("保存成功");
		}
		return BaseRespone.error("保存失败");
	}
	
	@Override
	public BaseRespone delAppraise(String appraiseId) {
		int row = appraiseMapper.deleteUpdate(appraiseId, "appraise_delete");
		if(row > 0) {
			return BaseRespone.success("删除成功");
		}
		return BaseRespone.error("删除失败");
	}

	@Override
	public BaseRespone reAppraise(String appraiseId) {
		List<WorkInfo> fenzi = new ArrayList<WorkInfo>();
		List<WorkInfo> fenmu = new ArrayList<WorkInfo>();
		BsAppraise info = appraiseMapper.selectByKey(appraiseId);
		BsScoreRecord sRecord = scoreRecordMapper.selectByKey(info.getAppraiseRecordId());
		if(null == sRecord) {
			return BaseRespone.error("该学生的课程目标项暂未设置");
		}
		if(null == sRecord.getRecordScore()) {
			return BaseRespone.error("该学生的课程目标项暂未打分");
		}
		BsCourseTarget t = targetMapper.selectByKey(info.getAppraiseTargetId());
		// 目标项的打分 x  目标项的权重
		fenzi.add(new WorkInfo(sRecord.getRecordScore(), t.getTargetWeight()));
		// 目标项的分值 x  目标项的权重
		fenmu.add(new WorkInfo(t.getTargetScore(), t.getTargetWeight()));
		
		MyMap mm = new MyMap().put("recordAppraiseId", appraiseId).put("recordDelete", 0);
		List<BsAppraiseRecord> rlist = recordMapper.selectAllNotPage(mm);
		try {
			for (BsAppraiseRecord arecord : rlist) {
				// 目标项的打分 x  目标项的权重
				fenzi.add(new WorkInfo(arecord.getRecordMark(), arecord.getRecordWeight()));
				// 目标项的分值 x  目标项的权重
				fenmu.add(new WorkInfo(arecord.getRecordScore(), arecord.getRecordWeight()));
			}
		} catch (Exception e) {
			log.error("达成度加载异常：{}", e);
		}
		try {
			BigDecimal fenziTotal = new BigDecimal(0);
			BigDecimal fenmuTotal = new BigDecimal(0);
			
			for (WorkInfo winfo : fenzi) {
				fenziTotal = fenziTotal.add(winfo.result());
			}
			
			for (WorkInfo winfo : fenmu) {
				fenmuTotal = fenmuTotal.add(winfo.result());
			}
			BigDecimal mark = fenziTotal.divide(fenmuTotal, 2, BigDecimal.ROUND_DOWN);
			info.setAppraiseScore(mark);
			appraiseMapper.updateSelective(info);
			return BaseRespone.success("计算成功");
		} catch (Exception e) {
			log.error("达成度计算异常：{}", e);
		}
		return BaseRespone.error("计算异常");
	}
	
	@Override
	public TableRespone getRecords(String appraiseId) {
		MyMap mm = new MyMap().put("recordAppraiseId", appraiseId).put("recordDelete", 0);
		List<BsAppraiseRecord> list = recordMapper.selectAllNotPage(mm);
		/*List<BsAppraiseRecordVo> clist = new ArrayList<BsAppraiseRecordVo>();
		if(list.size() > 0) {
			for (BsAppraiseRecord record : list) {
				BsCourseTarget t = targetMapper.selectByKey(record.getRecordTargetId());
				clist.add(new BsAppraiseRecordVo(record, t));
			}
		}*/
		return new TableRespone(list, list.size());
	}
	
	@Override
	public BaseRespone saveRecord(BsAppraiseRecord record) {
		int row = 0;
		BsAppraiseRecord info = recordMapper.selectByKey(record.getRecordId());
		BsAppraiseRecord hasrecord = new BsAppraiseRecord();
		hasrecord.setRecordAppraiseId(record.getRecordAppraiseId());
		//BsAppraiseRecord hasinfo = recordMapper.selectByInfo(hasrecord);
		if(null == info) {
			/*if(null != hasinfo) {
				return BaseRespone.error("已存在该目标项");
			}*/
			record.setRecordId(MyTools.getUUID());
			record.setRecordTime(new Date());
			record.setRecordDelete(0);
			row = recordMapper.insertSelective(record);
		}else {
			row = recordMapper.updateSelective(record);
		}
		if(row > 0) {
			/*if(null != hasinfo && !hasinfo.getRecordId().equals(record.getRecordId())) {
				return BaseRespone.error("已存在该目标项");
			}
			BigDecimal fenzi = new BigDecimal(0);
			BigDecimal fenmu = new BigDecimal(0);
			MyMap mm = new MyMap().put("recordAppraiseId", record.getRecordAppraiseId()).put("recordDelete", 0);
			List<BsAppraiseRecord> rlist = recordMapper.selectAllNotPage(mm);
			try {
				for (BsAppraiseRecord arecord : rlist) {
					BsCourseTarget t = targetMapper.selectByKey(arecord.getRecordTargetId());
					fenzi = fenzi.add(arecord.getRecordScore().multiply(t.getTargetWeight().divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN)));
					fenmu = fenmu.add(t.getTargetScore().multiply(t.getTargetWeight().divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN)));
				}
			} catch (Exception e) {
				log.error("达成度计算异常：{}", e);
			}
			if(fenzi.intValue() > 0 && fenmu.intValue() > 0) {
				BsAppraise appraise = new BsAppraise();
				appraise.setAppraiseId(record.getRecordAppraiseId());
				BigDecimal after = fenzi.divide(fenmu, 2, BigDecimal.ROUND_DOWN);
				appraise.setAppraiseScore(after);
				appraiseMapper.updateSelective(appraise);
			}*/
			reAppraise(record.getRecordAppraiseId());
			return BaseRespone.success("保存成功");
		}
		return BaseRespone.error("保存失败");
	}
	
	@Override
	public BaseRespone delRecord(String recordId) {
		int row = recordMapper.deleteUpdate(recordId, "record_delete");
		if(row > 0) {
			return BaseRespone.success("删除成功");
		}
		return BaseRespone.error("删除失败");
	}

	@Override
	public TableRespone getDegrees(String studentId, String courseId, String targetId, String remark, String date,
			int page, int size) {
		List<DegreeInfo> dlist = appraiseMapper.selectDegrees(studentId, courseId, targetId, remark, date, page, size);
		int count = appraiseMapper.selectDegreeCount(studentId, courseId, targetId, remark, date);
		return new TableRespone(dlist, count);
	}
    
}
